<script setup lang="tsx">
import { ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, SearchIcon, Delete1Icon } from 'tdesign-icons-vue-next';
import { getList, edit, getInfo, Delete } from '@/api/task/taskAdmin';
import UpLoadFile from '@/components/upLoadFile/index.vue';
const addDateRange = inject<typeof addDateRange>('addDateRange');
const { t } = useI18n();

const data = ref([]);
const columns = [
  {
    colKey: 'row-select',
    type: 'multiple' as const,
    width: 50,
  },
  {
    title: 'ID',
    colKey: 'taskId',
  },
  {
    title: '任务级别',
    colKey: 'taskLevel',
  },
  {
    title: '品牌',
    colKey: 'taskClass',
  },
  {
    title: '视频链接',
    colKey: 'linkInfo',
  },
  {
    title: '问题',
    colKey: 'question',
  },
  {
    title: '当前状态',
    colKey: 'status',
  },
  {
    title: '添加时间',
    colKey: 'addTime',
  },
  {
    title: '是否推荐',
    colKey: 'isRecommend',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  taskId: string | number | null;
  taskLevel: string | null;
  status: string | number | null;
  linkInfo: string | null;
  taskClass: string | number | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  taskId: undefined,
  taskLevel: undefined,
  status: undefined,
  linkInfo: undefined,
  taskClass: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        批量导入
      </t-button>
      <t-button theme="danger" icon={() => <Delete1Icon />} onClick={() => deleteClickOp(deleteId.value, true)}>
        批量删除
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.taskId} placeholder="任务ID" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-select v-model={queryForm.value.taskLevel} placeholder="任务级别">
        {gradeList.value?.map((item) => (
          <t-option key={item.grade.toString()} label={item.name} value={item.grade.toString()} />
        ))}
      </t-select>
      <t-input v-model={queryForm.value.linkInfo} placeholder="视频链接" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.taskClass} placeholder="品牌" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-date-range-picker v-model={dateRange.value} placeholder="发布时间" />
      <t-select v-model={queryForm.value.status} placeholder="状态">
        <t-option key={0} label="进行中" value={0} />
        <t-option key={1} label="已结束" value={1} />
      </t-select>
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      v-model:selectedRowKeys={deleteId.value}
      rowKey="taskId"
      onUnGetList={unGetList}
    >
      {{
        taskLevel: (slotProps: any) => <div>{getName('grade', slotProps.row.taskLevel, gradeList.value, 'name')}</div>,
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 0 ? 'primary' : 'success'} variant="light">
            {slotProps.row.status == 0 ? '进行中' : '已结束'}
          </t-tag>
        ),
        isRecommend: (slotProps: any) => (
          <t-switch
            key={slotProps.row.taskId}
            value={slotProps.row.isRecommend}
            onChange={() => unEditIsRecommend(slotProps)}
            size="large"
            customValue={[1, 0, null]}
            label={['是', '否']}
          ></t-switch>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetList();
const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  dateRange.value = [];
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const fileData = ref();
const upLoadBox = ref(false);
const upload = ref();
const unAdd = async () => {
  upLoadBox.value = true;
};

const onConfirmUpload = async () => {
  upload.value.uploadFiles();
};

const success = () => {
  upLoadBox.value = false;
  fileData.value = undefined;
  unGetList();
};

// 详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.taskId);
    formObj.show(
      '编辑任务',
      {
        ...res.data,
      },
      '编辑任务',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑任务',
  '编辑任务',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {},
  '30%',
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.taskId];
};

const onCancel = () => {
  if (deleteId.value.length < 2) {
    deleteId.value = [];
  }
};

// 修改推荐状态
const unEditIsRecommend = async (slotProps: any) => {
  slotProps.row.isRecommend = slotProps.row.isRecommend == 1 ? 0 : 1;
  edit(slotProps.row).then(() => {
    MessagePlugin.success('操作成功');
    unGetList();
  });
};

// 等级列表
import { useGradeStore } from '@/store/modules/member';
const gradeStore = useGradeStore();
const gradeList = ref<any[]>([]);
gradeList.value = gradeStore.gradeList;

const getName = (lid: any, id: any, list: any, name: any) => {
  const item = list.find((item: { [x: string]: any }) => item[lid] == id);
  return item?.[name] ?? id;
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 编辑任务对话框 -->
        <template v-if="item == '编辑任务'">
          <t-form-item label="品牌" name="taskClass">
            <t-input v-model="formData.taskClass" :style="{ width: '580px' }" placeholder="请输入品牌" />
          </t-form-item>
          <t-form-item label="视频链接" name="linkInfo">
            <t-input v-model="formData.linkInfo" :style="{ width: '580px' }" placeholder="请输入视频链接" />
          </t-form-item>
          <t-form-item label="图片链接" name="image">
            <t-input v-model="formData.image" :style="{ width: '580px' }" placeholder="请输入图片链接" />
          </t-form-item>
          <t-form-item label="图片预览" name="image">
            <img style="max-width: 200px" :src="formData.image" alt="" />
          </t-form-item>
          <t-form-item label="任务简介" name="content">
            <t-textarea v-model="formData.content" placeholder="请输入内容" />
          </t-form-item>
          <t-form-item label="问题" name="question">
            <t-textarea v-model="formData.question" placeholder="请输入问题" />
          </t-form-item>
          <t-form-item label="答案1" name="answer1">
            <t-textarea v-model="formData.answer1" placeholder="请输入答案1" />
          </t-form-item>
          <t-form-item label="答案2" name="answer2">
            <t-textarea v-model="formData.answer2" placeholder="请输入答案2" />
          </t-form-item>
          <t-form-item label="正确答案" name="rightAnswer">
            <t-radio-group v-model="formData.rightAnswer">
              <t-radio :value="1">答案1</t-radio>
              <t-radio :value="2">答案2</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item label="任务级别" name="taskLevel">
            <t-radio-group v-model="formData.taskLevel">
              <t-radio v-for="item in gradeList" :value="item.grade.toString()">{{ item.name }}</t-radio>
            </t-radio-group>
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-radio-group v-model="formData.status">
              <t-radio :value="0">进行中</t-radio>
              <t-radio :value="1">已结束</t-radio>
            </t-radio-group>
          </t-form-item>
        </template>
      </template>
    </FormDialogGroup>
    <!-- 批量导入 -->
    <t-dialog v-model:visible="upLoadBox" title="批量导入" @confirm="onConfirmUpload" width="50%">
      <div class="row">
        <div class="hint">EXCEL文件格式（注意：仅Sheet1有效）</div>
        <img src="@/assets/taskimport.jpg" alt="" />
      </div>
      <UpLoadFile
        v-if="upLoadBox"
        @success="success"
        v-model:file="fileData"
        ref="upload"
        :axios="'/task/base/import'"
      ></UpLoadFile>
    </t-dialog>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
      :on-cancel="onCancel"
    />
  </div>
</template>

<style lang="less" scoped>
.row {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-bottom: 24px;
  .hint {
    font-size: 16px;
    color: red;
  }
  img {
    border: 2px solid #ddd;
  }
}
</style>
